import { Metadata } from 'next';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Progress } from '@/components/ui/progress';
import {
  SolutionsBreadcrumb,
  SolutionsNavigationSimple,
} from '@/components/solutions-navigation';
import { CaseStudies, caseStudiesByIndustry } from '@/components/case-studies';
import {
  Database,
  GitBranch,
  Shield,
  Layers,
  Clock,
  CheckCircle,
  ArrowRight,
  FileText,
} from 'lucide-react';

export const metadata: Metadata = {
  title: '分布式账本解决方案 | CActor金融科技',
  description:
    'CActor分布式账本系统：事件溯源、CQRS架构、数据一致性保证的企业级解决方案',
};

/**
 * 分布式账本解决方案页面
 * 展示CActor在分布式账本领域的完整技术方案
 */
export default function DistributedLedgerPage() {
  const systemFeatures = [
    { label: '事件存储容量', value: '10TB+', progress: 95 },
    { label: '查询响应时间', value: '< 50ms', progress: 92 },
    { label: '数据一致性', value: '100%', progress: 100 },
    { label: '水平扩展能力', value: '1000+ 节点', progress: 98 },
  ];

  const architectureComponents = [
    {
      name: '事件存储Actor',
      description: '不可变事件流存储',
      icon: Database,
      color: 'bg-blue-500',
      details: ['事件持久化', '快照管理', '版本控制'],
    },
    {
      name: '命令处理Actor',
      description: '业务命令验证和处理',
      icon: GitBranch,
      color: 'bg-green-500',
      details: ['命令验证', '业务规则', '状态更新'],
    },
    {
      name: '查询投影Actor',
      description: '读模型构建和维护',
      icon: Layers,
      color: 'bg-purple-500',
      details: ['视图构建', '索引优化', '缓存管理'],
    },
    {
      name: '一致性协调Actor',
      description: '分布式一致性保证',
      icon: Shield,
      color: 'bg-red-500',
      details: ['共识算法', '冲突解决', '状态同步'],
    },
  ];

  const eventSourcingFlow = [
    { step: 1, title: '命令接收', description: '接收业务命令请求' },
    { step: 2, title: '验证处理', description: '验证命令合法性' },
    { step: 3, title: '事件生成', description: '生成领域事件' },
    { step: 4, title: '事件存储', description: '持久化到事件流' },
    { step: 5, title: '投影更新', description: '更新读模型视图' },
  ];

  return (
    <div className="min-h-screen bg-gradient-to-br from-green-50 to-emerald-100 dark:from-slate-900 dark:to-slate-800">
      {/* Breadcrumb */}
      <div className="max-w-7xl mx-auto px-4 pt-6">
        <SolutionsBreadcrumb />
      </div>

      {/* Hero Section */}
      <section className="relative py-20 px-4">
        <div className="max-w-7xl mx-auto">
          <div className="text-center mb-12">
            <Badge variant="outline" className="mb-4">
              <Database className="mr-2 h-4 w-4" />
              分布式账本解决方案
            </Badge>
            <h1 className="text-4xl md:text-6xl font-bold mb-6 bg-gradient-to-r from-green-600 to-emerald-600 bg-clip-text text-transparent">
              事件溯源账本系统
            </h1>
            <p className="text-xl text-muted-foreground mb-8 max-w-3xl mx-auto">
              基于CActor框架和事件溯源模式构建的分布式账本系统，提供完整的数据可追溯性、强一致性保证和水平扩展能力
            </p>
          </div>

          {/* System Features */}
          <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-16">
            {systemFeatures.map((feature, index) => (
              <Card
                key={index}
                className="text-center bg-white/80 dark:bg-slate-800/80 backdrop-blur-sm border-0"
              >
                <CardHeader className="pb-2">
                  <CardTitle className="text-2xl font-bold text-green-600">
                    {feature.value}
                  </CardTitle>
                  <CardDescription>{feature.label}</CardDescription>
                </CardHeader>
                <CardContent>
                  <Progress value={feature.progress} className="h-2" />
                </CardContent>
              </Card>
            ))}
          </div>
        </div>
      </section>

      {/* Event Sourcing Flow */}
      <section className="py-16 px-4">
        <div className="max-w-7xl mx-auto">
          <div className="text-center mb-12">
            <h2 className="text-3xl font-bold mb-4">事件溯源处理流程</h2>
            <p className="text-lg text-muted-foreground">
              完整的CQRS + Event Sourcing架构实现
            </p>
          </div>

          <div className="flex flex-col md:flex-row items-center justify-between gap-4 mb-12">
            {eventSourcingFlow.map((item, index) => (
              <div
                key={index}
                className="flex flex-col items-center text-center"
              >
                <div className="bg-green-500 text-white rounded-full w-12 h-12 flex items-center justify-center font-bold mb-4">
                  {item.step}
                </div>
                <h4 className="font-semibold mb-2">{item.title}</h4>
                <p className="text-sm text-muted-foreground max-w-32">
                  {item.description}
                </p>
                {index < eventSourcingFlow.length - 1 && (
                  <ArrowRight className="hidden md:block h-6 w-6 text-muted-foreground mt-4 absolute translate-x-20" />
                )}
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* Architecture Components */}
      <section className="py-16 px-4">
        <div className="max-w-7xl mx-auto">
          <div className="text-center mb-12">
            <h2 className="text-3xl font-bold mb-4">核心架构组件</h2>
            <p className="text-lg text-muted-foreground">
              基于Actor模型的分布式账本核心组件
            </p>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
            {architectureComponents.map((component, index) => {
              const IconComponent = component.icon;
              return (
                <Card
                  key={index}
                  className="group hover:shadow-lg transition-all duration-300 bg-white/80 dark:bg-slate-800/80 backdrop-blur-sm border-0"
                >
                  <CardHeader>
                    <div className="flex items-center gap-4 mb-4">
                      <div
                        className={`p-3 rounded-lg ${component.color} text-white`}
                      >
                        <IconComponent className="h-6 w-6" />
                      </div>
                      <div>
                        <CardTitle className="text-xl">
                          {component.name}
                        </CardTitle>
                        <CardDescription>
                          {component.description}
                        </CardDescription>
                      </div>
                    </div>
                  </CardHeader>
                  <CardContent>
                    <div className="space-y-2">
                      {component.details.map((detail, idx) => (
                        <div key={idx} className="flex items-center gap-2">
                          <CheckCircle className="h-4 w-4 text-green-500" />
                          <span className="text-sm">{detail}</span>
                        </div>
                      ))}
                    </div>
                  </CardContent>
                </Card>
              );
            })}
          </div>
        </div>
      </section>

      {/* Technical Implementation */}
      <section className="py-16 px-4">
        <div className="max-w-7xl mx-auto">
          <Tabs defaultValue="event-store" className="w-full">
            <TabsList className="grid w-full grid-cols-4">
              <TabsTrigger value="event-store">事件存储</TabsTrigger>
              <TabsTrigger value="cqrs">CQRS实现</TabsTrigger>
              <TabsTrigger value="consistency">一致性保证</TabsTrigger>
              <TabsTrigger value="scaling">扩展策略</TabsTrigger>
            </TabsList>

            <TabsContent value="event-store" className="mt-6">
              <Card className="bg-white/80 dark:bg-slate-800/80 backdrop-blur-sm border-0">
                <CardHeader>
                  <CardTitle>事件存储实现</CardTitle>
                  <CardDescription>
                    不可变事件流的存储和管理机制
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="bg-slate-900 text-green-400 p-6 rounded-lg font-mono text-sm overflow-x-auto">
                    <pre>{`// 事件存储Actor实现
class EventStoreActor extends CActor {
  constructor() {
    super()
    this.eventStreams = new Map()
    this.snapshots = new Map()
  }

  // 追加事件到流
  async appendEvents(streamId: string, events: Event[], expectedVersion: number): Promise<AppendResult> {
    const stream = this.getOrCreateStream(streamId)
    
    // 乐观并发控制
    if (stream.version !== expectedVersion) {
      return { success: false, error: 'VERSION_CONFLICT' }
    }

    // 原子性追加事件
    const newEvents = events.map((event, index) => ({
      ...event,
      streamId,
      version: stream.version + index + 1,
      timestamp: Date.now(),
      eventId: generateEventId()
    }))

    await this.persistEvents(newEvents)
    stream.events.push(...newEvents)
    stream.version += events.length

    // 通知投影更新
    await this.notifyProjections(streamId, newEvents)
    
    return { success: true, newVersion: stream.version }
  }

  // 读取事件流
  async readEvents(streamId: string, fromVersion: number = 0): Promise<Event[]> {
    const stream = this.eventStreams.get(streamId)
    if (!stream) return []

    return stream.events.filter(event => event.version > fromVersion)
  }

  // 创建快照
  async createSnapshot(streamId: string, aggregateState: unknown): Promise<void> {
    const snapshot = {
      streamId,
      version: this.getStreamVersion(streamId),
      state: aggregateState,
      timestamp: Date.now()
    }

    await this.persistSnapshot(snapshot)
    this.snapshots.set(streamId, snapshot)
  }
}`}</pre>
                  </div>
                </CardContent>
              </Card>
            </TabsContent>

            <TabsContent value="cqrs" className="mt-6">
              <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                <Card className="bg-white/80 dark:bg-slate-800/80 backdrop-blur-sm border-0">
                  <CardHeader>
                    <CardTitle className="flex items-center gap-2">
                      <GitBranch className="h-5 w-5" />
                      命令端 (Write Side)
                    </CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="space-y-4">
                      <div className="bg-blue-50 dark:bg-blue-900/20 p-4 rounded-lg">
                        <h4 className="font-semibold mb-2">命令处理流程</h4>
                        <ul className="space-y-2 text-sm">
                          <li>• 命令验证和授权</li>
                          <li>• 业务规则检查</li>
                          <li>• 聚合根状态重建</li>
                          <li>• 事件生成和存储</li>
                        </ul>
                      </div>
                      <div className="bg-green-50 dark:bg-green-900/20 p-4 rounded-lg">
                        <h4 className="font-semibold mb-2">优化特性</h4>
                        <ul className="space-y-2 text-sm">
                          <li>• 快照机制减少重建时间</li>
                          <li>• 批量事件处理</li>
                          <li>• 异步事件发布</li>
                        </ul>
                      </div>
                    </div>
                  </CardContent>
                </Card>

                <Card className="bg-white/80 dark:bg-slate-800/80 backdrop-blur-sm border-0">
                  <CardHeader>
                    <CardTitle className="flex items-center gap-2">
                      <Layers className="h-5 w-5" />
                      查询端 (Read Side)
                    </CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="space-y-4">
                      <div className="bg-purple-50 dark:bg-purple-900/20 p-4 rounded-lg">
                        <h4 className="font-semibold mb-2">投影构建</h4>
                        <ul className="space-y-2 text-sm">
                          <li>• 事件订阅和处理</li>
                          <li>• 多种视图模型构建</li>
                          <li>• 索引优化</li>
                          <li>• 缓存策略</li>
                        </ul>
                      </div>
                      <div className="bg-orange-50 dark:bg-orange-900/20 p-4 rounded-lg">
                        <h4 className="font-semibold mb-2">查询优化</h4>
                        <ul className="space-y-2 text-sm">
                          <li>• 预计算聚合数据</li>
                          <li>• 分页和排序支持</li>
                          <li>• 实时数据同步</li>
                        </ul>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              </div>
            </TabsContent>

            <TabsContent value="consistency" className="mt-6">
              <Card className="bg-white/80 dark:bg-slate-800/80 backdrop-blur-sm border-0">
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <Shield className="h-5 w-5" />
                    分布式一致性保证
                  </CardTitle>
                  <CardDescription>
                    确保分布式环境下的数据一致性
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                    <div className="text-center">
                      <div className="bg-blue-100 dark:bg-blue-900 p-4 rounded-lg mb-4">
                        <Clock className="h-8 w-8 mx-auto text-blue-600" />
                      </div>
                      <h4 className="font-semibold mb-2">最终一致性</h4>
                      <p className="text-sm text-muted-foreground">
                        通过事件传播实现最终一致性，保证系统的高可用性
                      </p>
                    </div>
                    <div className="text-center">
                      <div className="bg-green-100 dark:bg-green-900 p-4 rounded-lg mb-4">
                        <CheckCircle className="h-8 w-8 mx-auto text-green-600" />
                      </div>
                      <h4 className="font-semibold mb-2">强一致性</h4>
                      <p className="text-sm text-muted-foreground">
                        关键业务场景下的强一致性保证机制
                      </p>
                    </div>
                    <div className="text-center">
                      <div className="bg-purple-100 dark:bg-purple-900 p-4 rounded-lg mb-4">
                        <GitBranch className="h-8 w-8 mx-auto text-purple-600" />
                      </div>
                      <h4 className="font-semibold mb-2">冲突解决</h4>
                      <p className="text-sm text-muted-foreground">
                        智能冲突检测和自动解决策略
                      </p>
                    </div>
                  </div>
                </CardContent>
              </Card>
            </TabsContent>

            <TabsContent value="scaling" className="mt-6">
              <Card className="bg-white/80 dark:bg-slate-800/80 backdrop-blur-sm border-0">
                <CardHeader>
                  <CardTitle>水平扩展策略</CardTitle>
                  <CardDescription>
                    支持大规模分布式部署的扩展方案
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="space-y-6">
                    <div>
                      <h4 className="font-semibold mb-3">分片策略</h4>
                      <div className="bg-slate-100 dark:bg-slate-700 p-4 rounded-lg">
                        <ul className="space-y-2 text-sm">
                          <li>
                            • <strong>按聚合根分片：</strong>
                            每个聚合根的事件存储在同一分片
                          </li>
                          <li>
                            • <strong>一致性哈希：</strong>
                            动态分片分配和负载均衡
                          </li>
                          <li>
                            • <strong>分片迁移：</strong>支持在线分片重新分布
                          </li>
                          <li>
                            • <strong>跨分片查询：</strong>分布式查询协调和聚合
                          </li>
                        </ul>
                      </div>
                    </div>
                    <div>
                      <h4 className="font-semibold mb-3">复制策略</h4>
                      <div className="bg-slate-100 dark:bg-slate-700 p-4 rounded-lg">
                        <ul className="space-y-2 text-sm">
                          <li>
                            • <strong>主从复制：</strong>写入主节点，读取从节点
                          </li>
                          <li>
                            • <strong>多主复制：</strong>多个写入节点的冲突解决
                          </li>
                          <li>
                            • <strong>异步复制：</strong>高性能的异步数据同步
                          </li>
                          <li>
                            • <strong>故障切换：</strong>
                            自动故障检测和主节点切换
                          </li>
                        </ul>
                      </div>
                    </div>
                  </div>
                </CardContent>
              </Card>
            </TabsContent>
          </Tabs>
        </div>
      </section>

      {/* Security Features */}
      <section className="py-16 px-4 bg-white/50 dark:bg-slate-800/50">
        <div className="max-w-7xl mx-auto">
          <div className="text-center mb-12">
            <h2 className="text-3xl font-bold mb-4">安全特性</h2>
            <p className="text-lg text-muted-foreground">企业级安全保障机制</p>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
            <Card className="text-center bg-white/80 dark:bg-slate-800/80 backdrop-blur-sm border-0">
              <CardHeader>
                <Shield className="h-12 w-12 mx-auto text-blue-600 mb-4" />
                <CardTitle className="text-lg">数据加密</CardTitle>
              </CardHeader>
              <CardContent>
                <p className="text-sm text-muted-foreground">
                  端到端加密，静态数据和传输数据全面保护
                </p>
              </CardContent>
            </Card>

            <Card className="text-center bg-white/80 dark:bg-slate-800/80 backdrop-blur-sm border-0">
              <CardHeader>
                <FileText className="h-12 w-12 mx-auto text-green-600 mb-4" />
                <CardTitle className="text-lg">审计日志</CardTitle>
              </CardHeader>
              <CardContent>
                <p className="text-sm text-muted-foreground">
                  完整的操作审计轨迹，支持合规性要求
                </p>
              </CardContent>
            </Card>

            <Card className="text-center bg-white/80 dark:bg-slate-800/80 backdrop-blur-sm border-0">
              <CardHeader>
                <CheckCircle className="h-12 w-12 mx-auto text-purple-600 mb-4" />
                <CardTitle className="text-lg">访问控制</CardTitle>
              </CardHeader>
              <CardContent>
                <p className="text-sm text-muted-foreground">
                  细粒度权限控制，基于角色的访问管理
                </p>
              </CardContent>
            </Card>

            <Card className="text-center bg-white/80 dark:bg-slate-800/80 backdrop-blur-sm border-0">
              <CardHeader>
                <Database className="h-12 w-12 mx-auto text-red-600 mb-4" />
                <CardTitle className="text-lg">数据完整性</CardTitle>
              </CardHeader>
              <CardContent>
                <p className="text-sm text-muted-foreground">
                  加密哈希验证，确保数据不被篡改
                </p>
              </CardContent>
            </Card>
          </div>
        </div>
      </section>

      {/* Customer Case Studies */}
      <div className="bg-white/50 dark:bg-slate-800/50">
        <CaseStudies
          studies={caseStudiesByIndustry['distributed-ledger']}
          title="客户成功案例"
          description="真实的分布式账本系统部署案例和业务价值"
        />
      </div>

      {/* CTA Section */}
      <section className="py-20 px-4">
        <div className="max-w-4xl mx-auto text-center">
          <h2 className="text-3xl font-bold mb-6">构建您的分布式账本系统</h2>
          <p className="text-lg text-muted-foreground mb-8">
            获取基于CActor的分布式账本解决方案，实现可靠的事件溯源架构
          </p>
          <div className="flex flex-col sm:flex-row gap-4 justify-center">
            <Button size="lg" className="bg-green-600 hover:bg-green-700">
              获取解决方案
            </Button>
            <Button size="lg" variant="outline">
              技术咨询
            </Button>
          </div>
        </div>
      </section>

      {/* Solutions Navigation */}
      <div className="max-w-7xl mx-auto px-4">
        <SolutionsNavigationSimple />
      </div>
    </div>
  );
}
